<template>
  <!--文件上传icon显示列表-->
  <div style="display: flex">
    <div v-for="item in iconList" :key="item.uid" style="margin-right: 5px">
      <a
        v-if="isPreviewShow(item.name) && typeof item.name === 'string'"
        :href="item.url"
        target="_blank"
        rel="noopener noreferrer"
      >
        <img :src="getImageSrc(item)" style="width: 30px; height: 30px" />
      </a>
      <img
        v-else-if="typeof item.name === 'string'"
        :src="getIconSrc(item.name)"
        style="width: 30px; height: 30px"
        @click="handleDownload(item)"
      />
    </div>
  </div>
</template>

<script>
  const fileSuffixList = [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'pdf',
    'ogg',
    'mp3',
    'wav',
    'mp4',
    'm4v',
    'webm',
    'zip',
  ];
  const imageSuffixList = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
  const videoSuffixList = ['mp4', 'avi', 'flv', 'mov', 'wmv', 'mkv'];
  export default {
    name: 'UploadIcon',
    props: {
      iconList: {
        type: Array,
        default: () => [],
      },
    },
    setup() {
      const getIconType = (fileName) => {
        // 文件后缀名,统一转为小写，作为icon类型使用
        const fileSuffix = fileName.split('.').pop().toLocaleLowerCase();
        return fileSuffixList.includes(fileSuffix) ? fileSuffix : 'file';
      };
      const getIconSrc = (fileName) => {
        return `assets/icons/${getIconType(fileName)}.svg`;
      };
      // 点击预览弹窗展示的（图片和视频）
      const isPreviewShow = (fileName) => {
        if (!fileName) {
          return;
        }
        const fileSuffix = fileName.split('.').pop().toLocaleLowerCase();
        return imageSuffixList.includes(fileSuffix) || videoSuffixList.includes(fileSuffix);
      };
      // 图片类型的
      const isImage = (fileName) => {
        const fileSuffix = fileName.split('.').pop()?.toLocaleLowerCase() ?? '';
        return imageSuffixList.includes(fileSuffix);
      };
      const getImageSrc = ({ name, url }) => {
        if (isImage(name)) {
          return url;
        } else {
          return getIconSrc(name);
        }
      };
      const handleDownload = ({ name, url }) => {
        fetch(url)
          .then((res) => res.blob())
          .then((blob) => {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(blob); // 创建下载的链接
            downloadElement.href = href;
            downloadElement.download = name; // 下载后文件名
            downloadElement.target = '_blank';
            downloadElement.style.display = 'none';
            document.body.appendChild(downloadElement);
            downloadElement.click(); // 点击下载
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href);
          });
      };
      return {
        getIconSrc,
        handleDownload,
        isImage,
        isPreviewShow,
        getImageSrc,
      };
    },
  };
</script>
